package cn.com.wxd.action.admin;

import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.wxd.action.AjaxResult;
import cn.com.wxd.action.ValidatorResult;
import cn.com.wxd.biz.user.UsersService;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.user.UsersInfo;
import cn.com.wxd.service.freemarker.TemplateFactor;
import cn.com.wxd.service.freemarker.TemplateType;
import cn.com.wxd.service.javamail.AsyncMailSender;
import cn.com.wxd.service.javamail.MailSender;
import cn.com.wxd.service.sms.SmsSentFactor;
import cn.com.wxd.service.sms.SmsSenter;
import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.CharValidator;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.util.service.MessageUtil;
import cn.com.wxd.util.RequestUtil;
import cn.com.wxd.util.action.AccessLogUtil;
import cn.com.wxd.util.service.ProjectInfo;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/6/2.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("/admin")
public class AdminCtl {

    private static final Logger log = LoggerFactory.getLogger(AdminCtl.class);
    @Resource
    private UsersService usersService;

    @RequestMapping("/index")
    public String index() {
        return "/admin/index";
    }

    /**
     * 后台登录页面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request, ModelMap map, String userName, String passWord,
                        String verCode) {
        String method = request.getMethod();
        if(!method.equalsIgnoreCase("post")){ // 如果不是post请求就返回登录页面
            return "/admin/login";
        }
        ValidatorResult valires = AdminCtlValidator.loginValidator(request, userName, passWord, verCode);
        if (!valires.isSuccess()) {
            map.put("actionError", valires.getMessage());
            map.put("userName", userName);
            return "/admin/login";
        }
        if (!usersService.login(request, userName, passWord)) {
            map.put("userName", userName);
            map.put("actionError", "用户名或密码错误！");
            return "/admin/login";
        }
        log.debug(userName + "上线了！");
        return "redirect:/admin/index";

    }

    /**
     * 申请账号页面
     *
     * @return
     */
    @RequestMapping("/applyfor")
    public String applyfor(HttpServletRequest request, ModelMap map, UsersInfo users, String userName, String password,
                           String rePassword, String verCode) {
        String method = request.getMethod();
        if(!method.equalsIgnoreCase("post")){ // 如果不是post请求就返回注册页面
            return "admin/applyfor";
        }
        ValidatorResult valires = AdminCtlValidator.applyforValidator(request, userName, password, rePassword, verCode);
        if (!valires.isSuccess()) {
            map.put("actionError", valires.getMessage());
            return "admin/applyfor";
        }
        if (usersService.queryUserB(userName)) {
            map.put("actionError", "用户已存在，请输入新的用户名！");
            return "admin/applyfor";
        }
        String ip = RequestUtil.getRemortIP(request);

        users.setPassWord(password);
        String time = DateUtil.getDatetimeStr();
        users.setCreateTime(time);
        users.setUserType("ADMIN");  //用户类型 管理员
        if (CharUtil.isEmpty(users.getNickName())) {
            users.setNickName(CharUtil.subStringByte("admin" + "_" + userName, 12));
        }
        users.setIsDisabled("Y");  //用户禁用

        AccountInfo account = new AccountInfo();
        account.setUserName(userName);
        account.setCreateTime(time);
        account.setType("APPLIY"); //普通注册
        account.setLalogIp(ip);
        account.setLalogTime(time);

        account.setUsersInfo(users);
        if (!usersService.addUser(account)) {
            map.put("actionError", "申请失败，请联系管理员！");
            return "admin/applyfor";
        }
        sentApplyMessage(users.getPhone()); //发送给客户的信息
        sentApplyMessage(users.getEmail());  //发送给客户的信息

        //TODO 发送给管理员的通知，未实现

        //申请管理员记录到日志
        AccessLogUtil.addUserOperationLog(account, "APPLYADMIN");

        map.put("message", "注册成功！ 请等待管理员审核！");
        return "/admin/message";
    }

    /**
     * 获取用户提示信息和未读信息数量
     * @return
     */
    @RequestMapping(value = "/prompt")
    @ResponseBody
    public AjaxResult prompt(HttpServletRequest request){
        return  AjaxResult.successResult(MessageUtil.getPrompt(request));
    }

    /**
     * 用户管理员申请，通知信息
     *
     * @param contact
     */
    private void sentApplyMessage(String contact) {
        //给用户发送邮件，通知用户注册正在审核。
        if (contact != null && CharValidator.isEmail(contact)) {
            MailSender ms = new AsyncMailSender();
            HashMap<String, String> mapDate = new HashMap<>();
            mapDate.put("projectName", ProjectInfo.getCompanyName());
            mapDate.put("dateTime", DateUtil.getDateStr());
            String emailcontent =
                    TemplateFactor.getTemplate(TemplateType.EMAILTEMP).getTemplate("adminapplyemail", mapDate);
            ms.send(contact, "申请" + ProjectInfo.getCompanyName() + "管理员邮件", emailcontent);
            //发送邮件了。
        }
        //给用户发送短信，通知用户注册正在审核。
        if (contact != null && CharValidator.isMobile(contact)) {
            SmsSenter ss = SmsSentFactor.getSenter();
            HashMap<String, String> mapDate = new HashMap<>();
            mapDate.put("projectName", ProjectInfo.getCompanyName());
            String smscontent = TemplateFactor.getTemplate(TemplateType.SMSTEMP).getTemplate("adminapplysms", mapDate);
            ss.asyncSent(contact, smscontent);
            //发送短信了。
        }
    }
}
